package com.kfm.loginIp.controller;

import com.kfm.loginIp.bean.IPInfo;
import com.kfm.loginIp.exception.UserException;
import com.kfm.loginIp.model.User;
import com.kfm.loginIp.service.UserService;
import com.kfm.loginIp.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Aurora雪
 */
@RestController
@CrossOrigin // 允许跨域
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IPInfo ipInfo;

    /**
     * 登录页面
     * @return
     */
    @GetMapping(value = {"/","/login"})
    public ModelAndView login() {
        return new ModelAndView("login");
    }


    /**
     * 登录
     * @param userInput
     * @param password
     * @param session
     * @param model
     * @param redirectAttributes
     * @return
     * @throws UserException
     */
    @PostMapping(value = {"/login"})
    public RespUtil login(String userInput, String password, HttpSession session, HttpServletRequest request,
                          Model model, RedirectAttributes redirectAttributes) throws UserException {
        if (userInput == null || password == null) {
            return RespUtil.error(205,"用户名或密码不能为空",null);
        }else {
            String privateKey = KeyStore.getInstance().getPrivateKey();//获取私钥
            //用私钥解密
            String username1 = RSAUtil.decryptWithPrivateKeyBlock(userInput, privateKey);
            String pass = RSAUtil.decryptWithPrivateKeyBlock(password, privateKey);
            String ip = IpUtil.getIpAddress(request);
            User user = userService.login(username1, pass);
            if (user != null) {
                redirectAttributes.addFlashAttribute("message", "登录成功");
                session.setAttribute("showCaptcha", false);
                // 清除错误次数
                ipInfo.getIpMap().remove(ip);
                request.getSession().setAttribute(Constant.LOGIN_USER, user);//将用户信息放入session中
                //重定向
                return RespUtil.ok("welcome");
            } else {
                RedirectAttributes attributes = redirectAttributes.addFlashAttribute("message", "用户名或密码错误");
                model.addAttribute(attributes);//将错误信息放入model中
                session.setAttribute("showCaptcha", true);//显示验证码
                ipInfo.getIpMap().put(ip, ipInfo.getIpMap().getOrDefault(ip, 0) + 1);//记录错误次数
                return RespUtil.error(400, "用户名或密码错误", null);
            }
        }
    }

    /**
     * 异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception e) {
        ModelAndView modelAndView = new ModelAndView("util/500");
        modelAndView.addObject("error", e.getMessage());
        return modelAndView;
    }

    /**
     * 欢迎页面
     * @return
     */
    @GetMapping("/welcome")
    public ModelAndView welcome() {
        return new ModelAndView("/welcome");
    }

    @GetMapping("util/403")
    public ModelAndView error403() {
        return new ModelAndView("util/403");
    }

    @GetMapping("/util/402")
    public ModelAndView error402() {
        return new ModelAndView("util/402");
    }
}


